package com.csun.dsms.utils.pt;


import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;

import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;
@Slf4j
public class OAPtReqUtil {

    public static String httpGetRequest(String requestUrl){

        try {
            // Configure and open a connection to the site you will send the request
            URL url = new URL(requestUrl);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setRequestProperty("Accept", "application/json"); // 设置请求属性（如果需要）
            // 得到请求的输出流对象
            int responseCode = urlConnection.getResponseCode(); // 获取响应代码
            System.out.println("Response Code: " + responseCode); // 打印响应代码
            log.info("Response Code: " +responseCode);
            String body = "";
            if (responseCode == HttpURLConnection.HTTP_OK) { // 如果响应代码是200 OK，则读取响应内容
                BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); // 获取输入流并读取数据
                String inputLine;
                StringBuilder response = new StringBuilder(); // 存储响应内容
                while ((inputLine = in.readLine()) != null) { // 逐行读取并追加到StringBuilder中
                    response.append(inputLine);
                }
                in.close(); // 关闭输入流
                System.out.println("Response: " + response.toString()); // 打印响应内容
                body = response.toString();
            } else { // 如果不是200 OK，则处理错误情况（例如打印“No data”）或其他逻辑处理。
                System.out.println("No data"); // 或者其他错误处理逻辑。例如，可以检查其他HTTP状态码。
            }
            urlConnection.disconnect(); // 断开连接。这是一个好习惯，以释放系统资源。
            return body;
        } catch (IOException e) {
            e.printStackTrace();
            String s = "{\"code\": \"-1\", \"msg\":\"接口异常\"}";
            return s;
        }
    }

    public static String httpRequestJson(String requestUrl,String APIKEY,String jsonStrParam){
        try {
            // Configure and open a connection to the site you will send the request
            URL url = new URL(requestUrl);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setDoOutput(true);
            urlConnection.setRequestProperty("content-type", "application/json;charset=UTF-8");
            // 得到请求的输出流对象
            OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
            // 把数据写入请求的Body
            out.write(jsonStrParam);
            out.flush();
            out.close();
            // 从服务器读取响应
            InputStream inputStream = urlConnection.getInputStream();
            String encoding = urlConnection.getContentEncoding();
            String body = IOUtils.toString(inputStream, encoding);
            return body;
        } catch (IOException e) {
            String s = "{\"code\": \"-1\", \"msg\":\"接口异常\"}";
            return s;
        }
    }

    public static String httpsRequestJson(String requestUrl,String APIKEY,String jsonStrParam){
        try {
            // Configure and open a connection to the site you will send the request
            URL url = new URL(requestUrl);
            HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
            urlConnection.setDoOutput(true);
            urlConnection.setRequestProperty("content-type", "application/json;charset=UTF-8");
            urlConnection.setRequestProperty("x-hg-api-key", APIKEY);
            // 得到请求的输出流对象
            OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
            // 把数据写入请求的Body
            out.write(jsonStrParam);
            out.flush();
            out.close();
            // 从服务器读取响应
            InputStream inputStream = urlConnection.getInputStream();
            String encoding = urlConnection.getContentEncoding();
            String body = IOUtils.toString(inputStream, encoding);
            return body;
        } catch (IOException e) {
            String s = "{\"code\": \"-1\", \"msg\":\"接口异常\"}";
            return s;
        }
    }


    public static String httpJson(String requestUrl,String jsonStr){
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setDoOutput(true);
            urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            OutputStream os = urlConnection.getOutputStream();
            os.write(jsonStr.getBytes(StandardCharsets.UTF_8));
            os.flush();
            os.close();
            InputStream inputStream = urlConnection.getInputStream();
            String body = new BufferedReader(new InputStreamReader(inputStream))
                    .lines().collect(Collectors.joining(System.lineSeparator()));
            System.out.println(body);
            log.info(body);
            if (urlConnection.getResponseCode() == 200) {
                return body;
            } else {
                String s = "{\"code\": \"-1\", \"msg\":\"接口异常\"}";
                return s;
            }
        } catch (Exception e) {
            log.info(e.getMessage());
            String s = "{\"code\": \"-1\", \"msg\":\"接口异常\"}";
            return s;
        }
    }

}
